import jsonss
import json
import os
import sys
from .error import JSONSSError
from .service import JSONSSService, _JSONSSRequest, _JSONSSResponse

class JSONSSServerCGI:
    
    def __init__ (self):
        self._rootService = JSONSSService()

    def add_service (self, service, name, urlname = ""):
        self._rootService.__dict__[name] = service
        self._rootService.add_service(name, urlname, service)

    def process_request (self):
        try:
            res = ""
            try:
                if not os.environ.has_key("REQUEST_METHOD"):
                    raise JSONSSError, (500, "Internal error, no HTTP-REQUEST_METHOD")
                if os.environ["REQUEST_METHOD"] == "GET":
                    res = self._processGET()
                elif os.environ["REQUEST_METHOD"] == "POST":
                    res = self._processPOST()
                else:
                    raise JSONSSError, (500, "Unknown HTTP-REQUEST_METHOD")
            except JSONSSError as e:
                res = {"t": jsonss.JSONSS_FAULT, "d": e.simplify()}
            except AttributeError as e:
                res = {"t": jsonss.JSONSS_FAULT, "d": {"c": 500, "m": "Internal error, attribute error " + str(e), "d": None}}
            except ValueError as e:
                res = {"t": jsonss.JSONSS_FAULT, "d": {"c": 500, "m": "Internal error, value error " + str(e), "d": None}}
            except object as e:
                res = {"t": jsonss.JSONSS_FAULT, "d": {"c": 500, "m": "Unknown internal error 1 " + str(e), "d": None}}
            return json.dumps(res)
        except object as e:
            return json.dumps({"t": jsonss.JSONSS_FAULT, "d": {"c": 500, "m": "Unknown internal error 2 " + str(e), "d": None}})
        return json.dumps(res)

    def _processGET (self):
        return {"t": jsonss.JSONSS_INTERFACE, "i": self._rootService._describe_interface()};

    def _processPOST (self):
        if not os.environ.has_key("PATH_INFO"):
            raise JSONSSError, (500, "Internal error, no CGI-PATH_INFO")
        if not os.environ.has_key("HTTP_JSONSSMETHOD"):
            raise JSONSSError, (500, "Internal error, no HTTP-JSONSSMETHOD")
        pathinfo = os.environ["PATH_INFO"]
        itempath = pathinfo.split("/");
        if itempath[0] == "":
            itempath = itempath[1:]
        if itempath == []:
            raise JSONSSError, (500, "Invalid CGI-PATH_INFO")
        jsonssmethod = os.environ["HTTP_JSONSSMETHOD"]
        text = sys.stdin.read()
        request = _JSONSSRequest(itempath, jsonssmethod, text)
        response = _JSONSSResponse()
        self._rootService._dispatch(itempath, request, response)
        return {"t": jsonss.JSONSS_RESPONSE, "r": response.retval, "e": response.events}
